package com.ironone.streaming;

import java.util.Arrays;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SlidingPaneLayout;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;
import com.ironone.streaming.application.CusAlrtBtnTypes;
import com.ironone.streaming.application.CusAlrtIconTypes;
import com.ironone.streaming.application.CustomAlertDialog;
import com.ironone.streaming.application.FormObject;
import com.ironone.streaming.application.MainApplication;
import com.ironone.streaming.comm.HTTPManager;
import com.ironone.streaming.evt.CallEventHandler;
import com.ironone.streaming.exception.ExceptionHandler;
import com.ironone.streaming.model.ModelMapper;
import com.ironone.streaming.model.OurShowsDataModel;
import com.ironone.streaming.model.ResponseDataModel;

public class MainMenuFragment extends Fragment {
	private UiLifecycleHelper uiHelper;
	private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
	private boolean pendingPublishReauthorization = false;

	View view;
	SlidingPaneLayout mPane;
	LoginButton fbLoginButton;	
	ImageView roundfb_profilepic;
	TextView textView_firstname;
	Button homebtn;
	TextView nowPlayingInfo_screenname;

	//Menu item1
	/*LinearLayout weeklypick_layout;
	TextView weeklypick_textView1;
	TextView weeklypick_textView2;
	LinearLayout weeklypick_ticker;*/

	//Menu item2
	LinearLayout events_layout;
	TextView events_textView1;
	TextView events_textView2;
	LinearLayout events_ticker;

	//Menu item3
	LinearLayout callus_layout;
	TextView callus_textView1;
	TextView callus_textView2;
	LinearLayout callus_ticker;

	//Menu item4
	LinearLayout ourshows_layout;
	TextView ourshows_textView1;
	TextView ourshows_textView2;
	LinearLayout ourshows_ticker;

	//Menu item5
	LinearLayout request_layout;
	TextView request_textView1;
	TextView request_textView2;
	LinearLayout request_ticker;

	@Override
	public void onSaveInstanceState(Bundle outState) {
		try {
			super.onSaveInstanceState(outState);
			outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
			uiHelper.onSaveInstanceState(outState);
			// uiHelper.onSaveInstanceState(outState);
		} catch (Exception e) {
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
			uiHelper = new UiLifecycleHelper(getActivity(), callback);
			uiHelper.onCreate(savedInstanceState);
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();
		}
	}


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.mainmenu_fragment, container, false);
		try {
			mPane = (SlidingPaneLayout) getActivity().findViewById(R.id.pane);
			nowPlayingInfo_screenname = (TextView) getActivity().findViewById(R.id.nowPlayingInfo_screenname);

			fbLoginButton = (LoginButton) view.findViewById(R.id.fbLoginButton);
			fbLoginButton.setPublishPermissions(Arrays.asList(new String[]{"user_likes", "user_birthday", "email", "user_location"}));		
			fbLoginButton.setBackgroundResource(R.drawable.facebookloginbutton);
			roundfb_profilepic = (ImageView) view.findViewById(R.id.roundfb_profilepic);
			textView_firstname = (TextView) view.findViewById(R.id.textView_firstname);
			homebtn = (Button) view.findViewById(R.id.homebtn);

			homebtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					aniamteScreeningText(" "); //Send space char if nothing to display.
					if(nowPlayingInfo_screenname.getText().equals(" ") || lastPane.equals(" ")){
					}else{
						//aniamteScreeningText(" ");  
						resetColors();
						getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.pane2, new AlbumArtFragment() , "pane2").commit();
					}
					mPane.closePane();
				}
			});

			fbLoginButton.setFragment(this);
			if (savedInstanceState != null) {
				pendingPublishReauthorization = savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
			}

			processMenu();
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();
		}
		return view;
	}

	String lastPane = "";  // Updates in call_us section only
	private void processMenu(){
		try {
			int txtView1Size = (int)FormObject.getInstance().getTextSize();
			int txtView2Size = (int) (FormObject.getInstance().getTextSize() * 0.75);

			// Menu item1
			/*weeklypick_layout = (LinearLayout) view.findViewById(R.id.weeklypick_layout);
			weeklypick_textView1 = (TextView) view.findViewById(R.id.weeklypick_textView1);
			weeklypick_textView2 = (TextView) view.findViewById(R.id.weeklypick_textView2);
			weeklypick_ticker = (LinearLayout) view.findViewById(R.id.weeklypick_ticker);
			weeklypick_textView1.setTextSize(txtView1Size);
			weeklypick_textView2.setTextSize(txtView2Size);

			weeklypick_layout.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					resetColors();
					weeklypick_ticker.setBackgroundColor(getResources().getColor(R.color.orange_special));
					return false;
				}				
			});

			weeklypick_layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {					
					String val = getString(R.string.weekly_pick);
					if(nowPlayingInfo_screenname.getText().equals(val) || lastPane.equals(val)){
					}else {
						lastPane = "";
						aniamteScreeningText(val);
						getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.pane2, new WeeklyPickFragment(), "pane2").commit();
					}
					mPane.closePane();
				}
			});*/

			// Menu item2
			events_layout = (LinearLayout) view.findViewById(R.id.events_layout);
			events_textView1 = (TextView) view.findViewById(R.id.events_textView1);
			events_textView2 = (TextView) view.findViewById(R.id.events_textView2);
			events_ticker = (LinearLayout) view.findViewById(R.id.events_ticker);
			events_textView1.setTextSize(txtView1Size);
			events_textView2.setTextSize(txtView2Size);

			events_layout.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					resetColors();
					events_ticker.setBackgroundColor(getResources().getColor(R.color.orange_special));
					return false;
				}				
			});

			events_layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {					
					String val = getString(R.string.events);
					if(nowPlayingInfo_screenname.getText().equals(val) || lastPane.equals(val)){
					}else {
						lastPane = "";
						aniamteScreeningText(val);
						getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.pane2, new EventsFragment(), "pane2").commit();
					}
					mPane.closePane();
				}
			});

			// Menu item3
			callus_layout = (LinearLayout) view.findViewById(R.id.callus_layout);
			callus_textView1 = (TextView) view.findViewById(R.id.callus_textView1);
			callus_textView2 = (TextView) view.findViewById(R.id.callus_textView2);
			callus_ticker = (LinearLayout) view.findViewById(R.id.callus_ticker);
			callus_textView1.setTextSize(txtView1Size);
			callus_textView2.setTextSize(txtView2Size);

			callus_layout.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					resetColors();
					callus_ticker.setBackgroundColor(getResources().getColor(R.color.orange_special));
					return false;
				}				
			});

			callus_layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					lastPane = nowPlayingInfo_screenname.getText().toString();
					aniamteScreeningText(getString(R.string.call_us));
<<<<<<< .mine
					
					CallEventHandler.getInsatance().setDjNum(getString(R.string.phone_no));
=======

					CallEventHandler.getInsatance().setDjNum(getString(R.string.phone_no));
>>>>>>> .r59
					CallEventHandler.getInsatance().callAlert(getActivity());
				}
			});

			// Menu item4
			ourshows_layout = (LinearLayout) view.findViewById(R.id.ourshows_layout);
			ourshows_textView1 = (TextView) view.findViewById(R.id.ourshows_textView1);
			ourshows_textView2 = (TextView) view.findViewById(R.id.ourshows_textView2);
			ourshows_ticker = (LinearLayout) view.findViewById(R.id.ourshows_ticker);
			ourshows_textView1.setTextSize(txtView1Size);
			ourshows_textView2.setTextSize(txtView2Size);

			ourshows_layout.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					resetColors();
					ourshows_ticker.setBackgroundColor(getResources().getColor(R.color.orange_special));
					return false;
				}				
			});

			ourshows_layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {					
					String val = getString(R.string.our_shows);
					if(nowPlayingInfo_screenname.getText().equals(val) || lastPane.equals(val)){
					}else {
						lastPane = "";
						aniamteScreeningText(val);
						getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.pane2, new OurShowsFragment(), "pane2").commit();
					}
					mPane.closePane();
				}
			});

			// Menu item5
			request_layout = (LinearLayout) view.findViewById(R.id.request_layout);
			request_textView1 = (TextView) view.findViewById(R.id.request_textView1);
			request_textView2 = (TextView) view.findViewById(R.id.request_textView2);
			request_ticker = (LinearLayout) view.findViewById(R.id.request_ticker);
			request_textView1.setTextSize(txtView1Size);
			request_textView2.setTextSize(txtView2Size);

			request_layout.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if(FormObject.getInstance().getTNLId() == null || FormObject.getInstance().getTNLId().equals("")
							|| getCurrentShowName() == null)
						return false;

					resetColors();
					request_ticker.setBackgroundColor(getResources().getColor(R.color.orange_special));
					return false;
				}				
			});

			request_layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String val = getString(R.string.request);
					/*if(nowPlayingInfo_screenname.getText().equals(val) || lastPane.equals(val)){
					}else {
						lastPane = "";
						aniamteScreeningText(val);
					}*/

					String msgData = "";
					if(FormObject.getInstance().getTNLId() == null || FormObject.getInstance().getTNLId().equals(""))
						msgData = getString(R.string.please_login_to_continue);

					if(!FormObject.getInstance().getFbLoginStatus()){
						msgData = getString(R.string.please_login_to_continue);
					}
					
					if(getCurrentShowName() == null){
						msgData = getString(R.string.no_shows_to_request);
					}

					if(msgData.equals("")){	
						if(nowPlayingInfo_screenname.getText().equals(val) || lastPane.equals(val)){
						}else {
							lastPane = "";
							aniamteScreeningText(val);  // Moved the code to top
							getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.pane2, new RequestFragment(), "pane2").commit();
						}
						mPane.closePane();	
					} else {
						CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.WIZERD);
						alertDialog.setTitleText(getActivity().getString(R.string.you_shall_not_pass));
						alertDialog.setMessageText(msgData);			
						alertDialog.show();
					}
				}
			});

		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();
		}
	}

	private String getCurrentShowName(){
		List<OurShowsDataModel> showModel = FormObject.getInstance().getShowsData();
		int currTime = FormObject.getInstance().getTime();
		int dayX = MainApplication.getDayIndex();

		for(int x=0; x < showModel.size(); x++) {
			// if show is not casting on today it will be ignored
			if(!showModel.get(x).showDays[dayX]) continue;

			if(showModel.get(x).showtime_start <= currTime && showModel.get(x).showtime_end >= currTime){
				return showModel.get(x).showName;
			}
		}
		return null;
	}

	Animation fadeIn;
	private void aniamteScreeningText(final String dText){
		fadeIn = new AlphaAnimation(0, 1);
		fadeIn.setInterpolator(new DecelerateInterpolator()); //add this
		fadeIn.setDuration(MainApplication.ANIME_DURATION);

		Animation fadeOut = new AlphaAnimation(1, 0);
		fadeOut.setInterpolator(new AccelerateInterpolator()); //and this
		fadeOut.setDuration(MainApplication.ANIME_DURATION);
		fadeOut.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation arg0) {
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				nowPlayingInfo_screenname.setText(dText);
				nowPlayingInfo_screenname.setAnimation(fadeIn);
			}
		});
		nowPlayingInfo_screenname.startAnimation(fadeOut);	
	}

	private void resetColors() {
		//weeklypick_ticker.setBackgroundColor(getResources().getColor(R.color.gray_dark));
		events_ticker.setBackgroundColor(getResources().getColor(R.color.gray_dark));
		callus_ticker.setBackgroundColor(getResources().getColor(R.color.gray_dark));
		ourshows_ticker.setBackgroundColor(getResources().getColor(R.color.gray_dark));
		request_ticker.setBackgroundColor(getResources().getColor(R.color.gray_dark));
	}

	@Override
	public void onPause() {
		try {
			super.onPause();
			uiHelper.onPause();
		} catch (Exception e) {
			/*CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();*/
		}
	}

	@Override
	public void onResume() {
		try {
			super.onResume();
			Session session = Session.getActiveSession();
			if (session != null && (session.isOpened() || session.isClosed())) {
				onSessionStateChange(session, session.getState(), null);
			}
			uiHelper.onResume();
		} catch (Exception e) {
			/*CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();*/
		}
	}


	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
		try {
			if (state.isOpened()) {

				if (session.isOpened()) {
					FormObject.getInstance().setFbLoginStatus(true);
					if (pendingPublishReauthorization && state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
						pendingPublishReauthorization = false;
					}

					if(textView_firstname.getText().toString().equals(getString(R.string.stranger)))
						new SyncFacebookDataAsync().execute();

					fbLoginButton.setBackgroundResource(R.drawable.menufblogoutbutton);		// Logout image
				}

			} else if (state.isClosed()) {
				FormObject.getInstance().setFbLoginStatus(false);
				session.closeAndClearTokenInformation();

				Bitmap drfault_bm = BitmapFactory.decodeResource(getResources(), R.drawable.default_profile_pic);
				Bitmap img1 = MainApplication.getRoundedRectBitmap(getActivity(), drfault_bm, true);
				roundfb_profilepic.setImageBitmap(img1);
				textView_firstname.setText(R.string.stranger);

				/*if(FormObject.getInstance().getFbLoginStatus())
					fbLoginButton.setBackgroundResource(R.drawable.menufblogoutbutton);		// Logout image
				else*/
				fbLoginButton.setBackgroundResource(R.drawable.menufbloginbutton);		// Login image
			}
		}catch(Exception e){
			FormObject.getInstance().setFbLoginStatus(false);
			FormObject.getInstance().setIsOneTimeExecuted(false);
			session.closeAndClearTokenInformation();

			Bitmap drfault_bm = BitmapFactory.decodeResource(getResources(), R.drawable.default_profile_pic);
			Bitmap img1 = MainApplication.getRoundedRectBitmap(getActivity(), drfault_bm, true);
			roundfb_profilepic.setImageBitmap(img1);
			textView_firstname.setText(R.string.stranger);

			fbLoginButton.setBackgroundResource(R.drawable.menufbloginbutton);		// Login image

			//Toast.makeText(getActivity(), R.string.error_fb_general, Toast.LENGTH_SHORT).show();
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.BIRD);
			alertDialog.setTitleText(getString(R.string.pigeon_s_taken_an_arrow));
			alertDialog.setMessageText(getString(R.string.error_fb_general));
			alertDialog.show();			
		}
	}

	public class SyncFacebookDataAsync extends AsyncTask<String, Void, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			try {
				if(FormObject.getInstance().getFbLoginStatus()){
					MainApplication.getFacebookProfileData(getActivity());

					// If TNL id is null, then do this again and get a TNL id. save it in FO
					if(FormObject.getInstance().getTNLId() == null || FormObject.getInstance().getTNLId().equals("")) 
						return sendFacebookDataToTNL();
				}
				return true;
			} catch (Exception e) {
				return false;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);

			if(FormObject.getInstance().getFbProfilePicture() != null){
				Bitmap convImg = MainApplication.getByteArrToBitmap(FormObject.getInstance().getFbProfilePicture());
				Bitmap img = MainApplication.getRoundedRectBitmap(getActivity(), convImg, false);
				if(img != null)
					roundfb_profilepic.setImageBitmap(img);
				else{
					Bitmap drfault_bm = BitmapFactory.decodeResource(getResources(), R.drawable.default_profile_pic);
					Bitmap img1 = MainApplication.getRoundedRectBitmap(getActivity(), drfault_bm, true);
					roundfb_profilepic.setImageBitmap(img1);
				}
			}else{
				//Put the default image here
				Bitmap drfault_bm = BitmapFactory.decodeResource(getResources(), R.drawable.default_profile_pic);
				Bitmap img1 = MainApplication.getRoundedRectBitmap(getActivity(), drfault_bm, true);
				roundfb_profilepic.setImageBitmap(img1);
			}			

			//String ss = FormObject.getInstance().getFbName();
			if(FormObject.getInstance().getFbName() != null && FormObject.getInstance().getFbName() != "")
				textView_firstname.setText(FormObject.getInstance().getFbName().split(" ")[0]);
			else
				textView_firstname.setText(R.string.stranger);
		}
	}

	private boolean sendFacebookDataToTNL() {
		try {
			HTTPManager httpmanager = new HTTPManager(getActivity());
			ResponseDataModel responseModel = httpmanager.sendFacebookUserData();

			if(responseModel.isError && responseModel.responseData == null){
				return false;
			}

			if(ModelMapper.getLoginDataModel(responseModel) == null){
				return false;
			} else {
				// Success
				MainApplication.foSaveChanges(getActivity());
				return true;
			}			
		} catch (Exception e) {
			return false;
		}
	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}
}
